import { TestConfig } from "../common/testConfig.js";
import { TestSimulateData } from "../testMgr/testSimulateData.js";
import {
    getSalesContractData,
    getSalesDetailInfo,
    updateOrCreateSalesContract,
    reviewSalesOrder, withdrawReviewAndDeleteOrder,
    getSalesContractCommoditiesListData
} from "../../network/api.js";
import { ApiReturnStruct, getApiData, CommunicationPageData, NetworkParser } from "../../network/communicationConverter.js";
import { Engine } from "../engine.js";
import { DataPage } from "../../network/communicationConverter.js";
import { DocType } from '../common/docDefinition.js';
import { SalesContract } from "../sales/salesContract.js";
import { OrderResult } from "../common/orderResult.js";
import { MessageUtil } from '@/utils/MessageUtil.js';
import { CommodityBatchWithTax } from "../sales/sales.js";
/**
 * 销售单相关UI操作类
 */
export class SalesUiAction {
    /**
     * 获取采购单商品明细列表数据
     * @param {Object} options - 参数选项
     * @param {string} options.orgId - 组织ID
     * @param {DataPage} options.pageInfo - 分页信息
     * @param {Object} [options.filter] - 过滤条件
     * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
     * @returns {Promise<ApiReturnStruct>}
     */
    async getSalesCommoditiesListByPage({
        orgId = null,
        pageInfo = null,
        filter = null,
        showLoadingPage = true
    }) {
        if (TestConfig.salesContractTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            // 模拟采购单商品明细数据
            simData.dataList = testSimulateData.simSalesCommodityBatch();

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
            return await getApiData(
                CommodityBatchWithTax.fromJson_metalSalesTradeMode, // 假设有对应的商品明细类
                orgId,
                pageInfo,
                getSalesContractCommoditiesListData,
                filter,
                showLoadingPage
            );
        }
    }

    /**
     * 获取销售单列表数据
     * @param {Object} options - 参数选项
     * @param {string} options.orgId - 组织ID
     * @param {DataPage} options.pageInfo - 分页信息
     * @param {Object} [options.filter] - 过滤条件
     * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
     * @returns {Promise<ApiReturnStruct>}
     */
    async getSalesContractData({
        orgId = null,
        pageInfo = null,
        filter = null,
        showLoadingPage = true
    }) {
        if (TestConfig.salesOrderTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            if (filter != null && filter['state'] === 0) {
                simData.dataList = testSimulateData.simSalesContractData(null);
            } else if (filter != null && filter['state'] === 1) {
                simData.dataList = testSimulateData.simSalesContractData(CommonOrderStatus.WaitReview);
            } else if (filter != null && filter['state'] === 2) {
                simData.dataList = testSimulateData.simSalesContractData(CommonOrderStatus.Passed);
            } else {
                simData.dataList = testSimulateData.simSalesContractData(null);
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
            return await getApiData(
                SalesContract.fromJson,
                orgId,
                pageInfo,
                getSalesContractData,
                filter,
                showLoadingPage
            );
        }
    }

    /**
     * 获取销售单详情
     * @param {string} orderId - 销售单ID
     * @returns {Promise<SalesContract|null>}
     */
    async getSalesDetailInfo(orderId) {
        if (TestConfig.salesOrderTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 模拟数据
            const testSimulateData = new TestSimulateData();
            let salesData = testSimulateData.simSalesContractData();

            // 查找匹配的元素
            let salesContract = salesData.find(item => item.id === orderId);
            if (salesContract) {
                return salesContract;
            }

            return testSimulateData.simSalesContractData()[0];
        } else {
            let res = await getSalesDetailInfo(orderId, Engine.profile.org.orgId);

            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, SalesContract.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * 创建或更新销售单
     * @param {SalesContract} salesContract - 销售单数据
     * @param {boolean} toAudit - 是否审核
     * @returns {Promise<OrderResult|null>}
     */
    async updateOrCreateSalesContract(salesContract, toAudit) {
        const res = await updateOrCreateSalesContract(salesContract, toAudit);

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * 审核销售单
     * @param {Array<string>} ids - 销售单ID列表
     * @param {string} orgId - 组织ID
     * @returns {Promise<any>}
     */
    async reviewSalesOrder(ids, orgId = null) {
        orgId = orgId ?? Engine.profile.org.orgId;

        const res = await reviewSalesOrder(ids, orgId);

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("审核销售单失败:" + apiResult.resErr);
            return apiResult;
        }

        return apiResult;
    }

    /**
     * 删除销售单
     * @param {Object} options - 参数选项
     * @param {string} options.orderId - 订单ID
     * @param {DocType} options.docType - 单据类型
     * @returns {Promise<any|null>}
     */
    async removeSalesOrder({
        orderId,
        docType
    }) {
        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除销售单据失败:" + apiResult.resErr);
            return apiResult;
        }

        return null;
    }

    /**
     * 显示销售单详情页面
     * @param {string} salesId - 销售单ID
     * @param {boolean} editMode - 是否编辑模式
     */
    async showSalesDetailPage(salesId, { editMode = false } = {}) {
        if (salesId) {
            uni.navigateTo({
                url: `/pages/sales/salesDetailPage?salesId=${salesId}&editMode=${editMode}`
            });
        } else {
            let store = Engine.profile?.getValideStore;
            let storeParam = "";
            if (store) {
                storeParam = "&storeId=" + store.id + "&storeName=" + store.name;
            }

            uni.navigateTo({
                url: `/pages/sales/salesDetailPage?editMode=${editMode}` + storeParam
            });
        }
    }
}